//
//  AppDelegate+Notification.m
//  haoshuimian365
//
//  Created by apple on 2017/6/30.
//  Copyright © 2017年 CYY. All rights reserved.
// 

#import "AppDelegate+Notification.h"
//#import "LGTabBarController.h"
#import <TPNS-iOS/XGPushPrivate.h>

#import <UserNotifications/UserNotifications.h>

#import "TUICallKit.h"
#import "DataBaseManager.h"
#import <TXLiteAVSDK_TRTC/TRTCCloud.h>
@interface AppDelegate()<UNUserNotificationCenterDelegate,XGPushDelegate,XGPushTokenManagerDelegate>

@end

@implementation AppDelegate (Notification)

-(void)registNotification:(UIApplication *)application andOptions:(NSDictionary *)launchOptions{
   //移动推送
    [[XGPush defaultManager] configureClusterDomainName:XGDomainName];
    [[XGPush defaultManager] startXGWithAccessID:XGAccessID accessKey:XGAccessKey delegate:self];
    //即使通讯

    
//    [[TUIKit sharedInstance] setupWithAppId:TUIAppId];
//    [TUILogin initWithSdkAppID:<#(int)#>]
//    [TUILogin initWithSdkAppID:TUIAppId];
//    [TUILogin initWithSdkAppID:<#(int)#>];

//    TIMLoginParam *param = [[TIMLoginParam alloc]init];
//    param.identifier = @"用户名2";
//    param.userSig = [GenerateTestUserSig genTestUserSig:@"用户名2"];
    
     
    //角标清理
//    [XGPush defaultManager].xgApplicationBadgeNumber = 0;
    

    /**  1、推送处理 */
    UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
    center.delegate = self;// 必须写代理，不然无法监听通知的接收与点击
    [center requestAuthorizationWithOptions:(UNAuthorizationOptionAlert | UNAuthorizationOptionBadge | UNAuthorizationOptionSound) completionHandler:^(BOOL granted, NSError * _Nullable error) {
        if (granted) {
            //点击允许
            [center getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings * _Nonnull settings) {
                NSLog(@"点击允许：%@", settings);
            }];
        } else {
            NSLog(@"点击不允许，注册失败");
        }
    }];
    
    /**  远程推送的内容 */
    [application registerForRemoteNotifications];
 
    [UIApplication sharedApplication].applicationIconBadgeNumber=0;
//    NSDictionary *dic = launchOptions[UIApplicationLaunchOptionsRemoteNotificationKey];
//    if (dic) {
//        self.remotNotifiDic = dic[@"customData"];
//    }
//    用户是否开启通知权限
//    [[XGPush defaultManager] deviceNotificationIsAllowed:^(BOOL isAllowed) {
//        if (isAllowed == YES) {
//
//        }else{
//
//        }
//    }];
}

//Tencent--获取XGToken
-(void)xgPushDidRegisteredDeviceToken:(NSString *)deviceToken xgToken:(NSString *)xgToken error:(NSError *)error{
    NSLog(@">>>Token ???>>>%@--%@",deviceToken,xgToken);
    [[NSUserDefaults standardUserDefaults] setObject:xgToken forKey:@"XGToken"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

//Tencent--接收消息
-(void)xgPushDidReceiveRemoteNotification:(id)notification withCompletionHandler:(void (^)(NSUInteger))completionHandler{
    NSDictionary *tempDic = nil;
    if ([notification isKindOfClass:[UNNotification class]]) {
        tempDic = ((UNNotification *)notification).request.content.userInfo;
        
    }else if ([notification isKindOfClass:[NSDictionary class]]){
        tempDic = notification;
    }
    
    if (tempDic) {
        NSDictionary *customDic = [ObjectTool jsonToObject:tempDic[@"custom"]];
        if ([customDic[@"pushtype"] isEqualToString:@"push102"]) {
            [[DataBaseManager shareInstance] insertSystemNewsWithDic:customDic sendTime:tempDic[@"xg"][@"pushTime"] messageid:tempDic[@"xg"][@"msgid"] userid:kUserId];
        }
    }
    [[NSNotificationCenter defaultCenter] postNotificationName:@"ReceiveNotification" object:nil];
    NSLog(@"接收消息>>>???>>>%@",tempDic);
}

//Tencent--点击回调
-(void)xgPushDidReceiveNotificationResponse:(id)response withCompletionHandler:(void (^)(void))completionHandler{
    NSDictionary *tempDic = nil;
    if ([response isKindOfClass:[UNNotificationResponse class]]) {
        tempDic = ((UNNotificationResponse *)response).notification.request.content.userInfo;
        
    }else if ([response isKindOfClass:[NSDictionary class]]){
        tempDic = response;
    }
    
    if (tempDic) {
        NSDictionary *customDic = [ObjectTool jsonToObject:tempDic[@"custom"]];
        if ([customDic[@"pushtype"] isEqualToString:@"push102"]) {
            [[DataBaseManager shareInstance] insertSystemNewsWithDic:customDic sendTime:tempDic[@"xg"][@"pushTime"] messageid:tempDic[@"xg"][@"msgid"] userid:kUserId];
        }
    }
    [[NSNotificationCenter defaultCenter] postNotificationName:@"ReceiveNotification" object:nil];
    NSLog(@"点击回调>>>???>>>%@",tempDic);
}

 
#pragma mark -- 注册远程推送
//获取deviceToken
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    [[NSUserDefaults standardUserDefaults] setValue:deviceToken forKey:@"deviceToken"];
    NSString *token = [[[[deviceToken description] stringByReplacingOccurrencesOfString:@"<"withString:@""] stringByReplacingOccurrencesOfString:@">" withString:@""]
                       stringByReplacingOccurrencesOfString:@" " withString:@""];
    NSLog(@">>deviceToken>>%@",token);
}

//注册用户通知设置失败：没有证书等等
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error{
    NSLog(@"远程通知注册失败: %@", error);
}


- (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler API_AVAILABLE(ios(10.0)){
    LGLogFunction;
    NSDictionary * userInfo = notification.request.content.userInfo;
    UNNotificationContent *content = notification.request.content;// 收到推送的消息内容
    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        NSLog(@"willPresent收到远程通知:{body:%@,\ntitle:%@,\nsubtitle:%@,\nbadge：%@,\nsound：%@,\nuserInfo：%@}",content.body,content.title,content.subtitle,content.badge,content.sound,userInfo);
    } else {
        // 判断为本地通知
        NSLog(@"willPresent收到本地通知:{body:%@,\ntitle:%@,\nsubtitle:%@,\nbadge：%@,\nsound：%@,\nuserInfo：%@}",content.body,content.title,content.subtitle,content.badge,content.sound,userInfo);
    }
//     需要执行这个方法，选择是否提醒用户，有Badge、Sound、Alert三种类型可以设置
    completionHandler(UNNotificationPresentationOptionBadge|UNNotificationPresentationOptionSound|UNNotificationPresentationOptionAlert);
}

- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)(void))completionHandler API_AVAILABLE(ios(10.0)){
    LGLogFunction;
    NSDictionary * userInfo = response.notification.request.content.userInfo;
    UNNotificationContent *content = response.notification.request.content; // 收到推送的消息内容
    if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        NSLog(@"didReceive收到远程通知:{body:%@,\ntitle:%@,\nsubtitle:%@,\nbadge：%@,\nsound：%@,\nuserInfo：%@}",content.body,content.title,content.subtitle,content.badge,content.sound,userInfo);
        if ([content.body containsString:@"服药时间到了，一定要按时按量"]) {
//            self.remotNotifiDic = @{@"pushtype":@"push107"};
        }

        if ([[NSString stringWithFormat:@"%@",userInfo[@"appData"]] length]>0) {
            NSDictionary *appData = [ObjectTool jsonToObject:userInfo[@"appData"]];
//            self.remotNotifiDic = appData[@"customData"];
        }

    }else{
        // 判断为本地通知
        NSLog(@"didReceive收到本地通知:{body:%@,\ntitle:%@,\nsubtitle:%@,\nbadge：%@,\nsound：%@,\nuserInfo：%@}",content.body,content.title,content.subtitle,content.badge,content.sound,userInfo);
        //服药提醒（本地通知）
        if ([content.body containsString:@"服药时间到了，一定要按时按量"]) {
//            self.remotNotifiDic = @{@"pushtype":@"push107"};
        }

        //系统通知
        NSString *msgid = [NSString stringWithFormat:@"%@",userInfo[@"rc"][@"mId"]];
        NSDictionary *systemNewsDic = [[DataBaseManager shareInstance] selectSystemNewsWithMessageid:msgid userid:kUserId];
        if (systemNewsDic && [[NSString stringWithFormat:@"%@",systemNewsDic] length]>10) {
            NSDictionary *contentDic = [ObjectTool jsonToObject:systemNewsDic[@"content"]];
//            self.remotNotifiDic = contentDic;
        }
    }
    completionHandler();  // 系统要求执行这个方法
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    LGLogFunction;
    if ([[NSString stringWithFormat:@"%@",userInfo[@"appData"]] length]>0) {
        NSDictionary *appData = [ObjectTool jsonToObject:userInfo[@"appData"]];
//        self.remotNotifiDic = appData[@"customData"];
    }
    completionHandler(UIBackgroundFetchResultNewData);
}


#pragma mark -- 接收新的消息
// 有新的消息---APP小红帽数量
- (void)didReceiveMessageNotification:(NSNotification *)notification{
    NSLog(@">didReceiveMessageNotification>>%@",notification.userInfo);
    [UIApplication sharedApplication].applicationIconBadgeNumber +=1;
}




@end
